package com.jandan.ui.client;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.FlexTable;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.core.Position;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.form.FormPanel;
import com.gwtext.client.widgets.form.TextArea;
import com.gwtext.client.widgets.form.TextField;
import com.gwtext.client.widgets.layout.VerticalLayout;
import com.jandan.ui.client.service.WordLibService;
import com.jandan.ui.client.service.WordLibServiceAsync;
import com.jandan.ui.model.CnAndSentence;
import com.jandan.ui.model.Word;

public class AddStrangeWordPanel extends Panel {
	private Word word;
	private FlexTable cnAndSentenceTable;
	private ILessonOperator lessonOperator;

	public AddStrangeWordPanel(ILessonOperator lessonOperator) {
		this.lessonOperator = lessonOperator;
		this.createComponent();
	}

	public AddStrangeWordPanel(ILessonOperator lessonOperator, Word word) {
		this.lessonOperator = lessonOperator;
		this.word = word;
		createComponent();
	}

	public void createComponent() {
		this.setLayout(new VerticalLayout(20));
		final FormPanel formPanel = new FormPanel();
		formPanel.setBorder(false);
		formPanel.setLabelAlign(Position.TOP);
		formPanel.setWidth(400);

		final TextField wordIDField = new TextField("单词ID", "wordID");
		
		wordIDField.setHideLabel(true);
		wordIDField.setVisible(false);

		// 英文单词
		final TextField wordEnField = new TextField("英文单词", "wordEn");
		wordEnField.setAllowBlank(false);
		wordEnField.setBlankText("英文单词不能为空");

		// 音标
		final TextField phoneticsField = new TextField("音标", "phonetics");
		phoneticsField.addClass("phonetics");
		formPanel.add(wordIDField);
		formPanel.add(wordEnField);
		formPanel.add(phoneticsField);

		// 中文含义
		cnAndSentenceTable = new FlexTable();
		formPanel.add(cnAndSentenceTable);

		if (word != null) {
			wordIDField.setValue("" + word.getWordID());
			wordEnField.setValue(word.getWordEn());
			phoneticsField.setValue(word.getPhonetics());
			List<CnAndSentence> csList = word.getCnAndSentenceList();
			if (csList != null) {
				for (int i = 0, n = csList.size(); i < n; i++) {
					int row = cnAndSentenceTable.getRowCount();
					row = cnAndSentenceTable.insertRow(row);
					cnAndSentenceTable.setWidget(row, 0,
							new CnAndSentencePanel(csList.get(i), row == 0));
				}
			}
		} else {
			int row = cnAndSentenceTable.getRowCount();
			row = cnAndSentenceTable.insertRow(row);
			cnAndSentenceTable.setWidget(row, 0, new CnAndSentencePanel(
					row == 0));
		}
		Button saveButton = new Button("保存");
		Button addCsButton = new Button("添加中文含义和例句");
		saveButton.addListener(new ButtonListenerAdapter() {

			@Override
			public void onClick(Button button, EventObject e) {
				// TODO Auto-generated method stub
				if (formPanel.getForm().isValid()) {
					if (word == null) {
						word = new Word();
						word.setWordID(-1);
						word
								.setCnAndSentenceList(new ArrayList<CnAndSentence>());
					}

					word.setWordEn(wordEnField.getText());
					word.setPhonetics(phoneticsField.getText());

					int row = cnAndSentenceTable.getRowCount();
					CnAndSentencePanel csPanel = null;
					String csID = null;
					String cn = null;
					String sentence = null;
					CnAndSentence cs = null;
					Iterator<CnAndSentence> it = null;
					CnAndSentence cc = null;
					for (int i = 0; i < row; i++) {
						csPanel = (CnAndSentencePanel) cnAndSentenceTable
								.getWidget(0, 0);
						if (csPanel != null) {
							csID = csPanel.getCsID();
							cn = csPanel.getCn();
							sentence = csPanel.getSentence();

							if (csID.length() <= 0) {
								cs = new CnAndSentence();
								cs.setCsID(-1);
								cs.setCn(cn);
								cs.setSentence(sentence);
								cs.setWordID(word.getWordID());
								word.getCnAndSentenceList().add(cs);
							} else {
								it = word
										.getCnAndSentenceList().iterator();
								while (it.hasNext()) {
									cc = it.next();
									
									if (cc.getCsID() != -1
											&& cc.getCsID() == Integer.parseInt(csID)) {
										cc.setCn(cn);
										cc.setSentence(sentence);
									}
								}
							}
						}

					}
					// displayTipInfo("正在添加生词" +
					// currentWord.getWord().getWordEn()
					// + "....");
					WordLibServiceAsync wordLibService = WordLibService.Util
							.getInstance();

					wordLibService.addStrangeWord(word,
							new AsyncCallback() {
								public void onFailure(Throwable caught) {
									// TODO Auto-generated method stub
									MessageBox.alert("添加生词错误");
								}

								public void onSuccess(Object result) {
									// TODO Auto-generated method stub
									MessageBox.alert("生词添加成功");
									lessonOperator
											.closeStrangePanel(getPanelID());
								}
							});
				}
			}
		});

		addCsButton.addListener(new ButtonListenerAdapter() {
			@Override
			public void onClick(Button button, EventObject e) {
				// TODO Auto-generated method stub
				int row = cnAndSentenceTable.getRowCount();
				row = cnAndSentenceTable.insertRow(row);
				cnAndSentenceTable.setWidget(row, 0, new CnAndSentencePanel(
						false));
			}
		});
		formPanel.setButtons(new Button[] { saveButton, addCsButton });
		formPanel.setButtonAlign(Position.LEFT);

		this.add(formPanel);
	}

	private class CnAndSentencePanel extends FormPanel {
		private TextField csIDField;
		private TextField cnField;
		private TextArea sentenceArea;
		private CnAndSentence cs;
		private boolean isFirst;

		public CnAndSentencePanel(boolean isFirst) {
			this.isFirst = isFirst;
			createComponent();
		}

		public CnAndSentencePanel(CnAndSentence cs, boolean isFirst) {
			this.isFirst = isFirst;
			this.cs = cs;
			this.createComponent();
		}

		private void createComponent() {
			this.setBorder(false);
			csIDField = new TextField();
			csIDField.setHideLabel(true);

			cnField = new TextField("中文含义");
			cnField.setAllowBlank(false);
			cnField.setBlankText("必须填写中文含义");
			cnField.setWidth(300);

			sentenceArea = new TextArea("例句");
			sentenceArea.setWidth(300);
			sentenceArea.setHeight(100);

			if (this.cs != null) {
				csIDField.setValue("" + cs.getCsID());
				cnField.setValue(cs.getCn());
				sentenceArea.setValue(cs.getSentence());
			}

			this.setLabelAlign(Position.TOP);

			this.add(csIDField);
			csIDField.setVisible(false);

			this.add(cnField);
			this.add(sentenceArea);

			if (!isFirst) {
				Button removeRowButton = new Button("删除");
				removeRowButton.addListener(new ButtonListenerAdapter() {

					@Override
					public void onClick(Button button, EventObject e) {
						// TODO Auto-generated method stub
						removeRow();
					}

				});

				this.setButtons(new Button[] { removeRowButton });
				this.setButtonAlign(Position.RIGHT);
			}
		}

		private void removeRow() {
			cnAndSentenceTable.remove(this);
		}

		public String getCsID() {
			return csIDField.getText();
		}

		public String getCn() {
			return cnField.getText().trim();
		}

		public String getSentence() {
			return sentenceArea.getText().trim();
		}
	}

	private String getPanelID() {
		return this.getId();
	}

}
